import React, { useState, useEffect } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@radix-ui/react-tabs';
import { CiSettings, CiExport, CiViewBoard, CiStreamOn, CiCloud } from 'react-icons/ci';
import {
  ToastProvider,
  ToastViewport,
  Toast,
  ToastTitle,
  ToastDescription,
} from './components/ui/toast';
import ProjectSettings from './components/ProjectSettings';
import UploadSection from './components/UploadSection';
import PreviewSection from './components/PreviewSection';
import NpmBuildSection from './components/NpmBuildSection';
import { getVsCodeApi } from './lib/vscode-api';

// 应用主组件
const App: React.FC = () => {
  // 状态管理
  const [devProjectPath, setDevProjectPath] = useState<string>(
    localStorage.getItem('devProjectPath') || (window as any).defaultPaths?.dev || ''
  );
  const [prodProjectPath, setProdProjectPath] = useState<string>(
    localStorage.getItem('prodProjectPath') || (window as any).defaultPaths?.prod || ''
  );
  const [privateKeyPath, setPrivateKeyPath] = useState<string>(
    localStorage.getItem('privateKeyPath') || (window as any).defaultPaths?.privateKey || ''
  );
  const [appid, setAppid] = useState<string>(
    localStorage.getItem('appid') || (window as any).defaultPaths?.appid || ''
  );
  const [type, setType] = useState<string>('miniProgram');
  const [loading, setLoading] = useState<boolean>(false);
  const [toast, setToast] = useState<{
    show: boolean;
    title: string;
    description: string;
    type: 'success' | 'error' | 'info';
  }>({
    show: false,
    title: '',
    description: '',
    type: 'info',
  });

  // 监听本地存储变化
  useEffect(() => {
    const handleStorageChange = () => {
      setDevProjectPath(localStorage.getItem('devProjectPath') || '');
      setProdProjectPath(localStorage.getItem('prodProjectPath') || '');
      setPrivateKeyPath(localStorage.getItem('privateKeyPath') || '');
    };

    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, []);

  // 发送消息到 VS Code 扩展
  const sendMessage = (message: any) => {
    getVsCodeApi().postMessage(message);
  };

  // 显示提示消息
  const showToast = (
    title: string,
    description: string,
    type: 'success' | 'error' | 'info' = 'info'
  ) => {
    setToast({ show: true, title, description, type });
    setTimeout(() => setToast({ ...toast, show: false }), 5000);
  };

  // 选择开发环境项目路径
  const handleSelectDevProjectPath = () => {
    sendMessage({ command: 'selectDevProjectPath' });
  };

  // 选择正式环境项目路径
  const handleSelectProdProjectPath = () => {
    sendMessage({ command: 'selectProdProjectPath' });
  };

  // 选择私钥路径
  const handleSelectPrivateKeyPath = () => {
    sendMessage({ command: 'selectPrivateKeyPath' });
  };

  // 保存配置
  const handleSaveConfig = () => {
    localStorage.setItem('appid', appid);
    localStorage.setItem('type', type);
    showToast('配置已保存', '项目配置已成功保存', 'success');
  };

  // 加载保存的配置
  useEffect(() => {
    const savedAppid = localStorage.getItem('appid');
    const savedType = localStorage.getItem('type');
    
    if (savedAppid) setAppid(savedAppid);
    if (savedType) setType(savedType);
  }, []);

  // 监听来自 VS Code 的消息
  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      const message = event.data;
      
      switch (message.command) {
        case 'devProjectPathSelected':
          setDevProjectPath(message.path);
          localStorage.setItem('devProjectPath', message.path);
          showToast('开发环境路径已选择', `已选择: ${message.path}`, 'success');
          break;
          
        case 'prodProjectPathSelected':
          setProdProjectPath(message.path);
          localStorage.setItem('prodProjectPath', message.path);
          showToast('正式环境路径已选择', `已选择: ${message.path}`, 'success');
          break;
          
        case 'privateKeyPathSelected':
          setPrivateKeyPath(message.path);
          localStorage.setItem('privateKeyPath', message.path);
          showToast('私钥路径已选择', `已选择: ${message.path}`, 'success');
          break;
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, []);

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-100 p-4">
      <div className="max-w-5xl mx-auto">
        <header className="mb-6">
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <CiStreamOn className="h-6 w-6" />
            Miniprogram CI Helper
          </h1>
          <p className="text-gray-500 dark:text-gray-400">
            可视化管理小程序 CI 流程
          </p>
        </header>

        <ToastProvider>
         <Tabs defaultValue="settings" className="w-full">
           <TabsList className="grid grid-cols-4 mb-6">
             <TabsTrigger value="settings" className="flex items-center gap-2">
               <CiSettings className="h-4 w-4" />
               设置
             </TabsTrigger>
             <TabsTrigger value="upload" className="flex items-center gap-2">
               <CiExport className="h-4 w-4" />
               上传
             </TabsTrigger>
             <TabsTrigger value="preview" className="flex items-center gap-2">
               <CiViewBoard className="h-4 w-4" />
               预览
             </TabsTrigger>
             <TabsTrigger value="npm" className="flex items-center gap-2">
               <CiStreamOn className="h-4 w-4" />
               构建 NPM
             </TabsTrigger>
           </TabsList>

            <TabsContent value="settings">
              <ProjectSettings
                devProjectPath={devProjectPath}
                prodProjectPath={prodProjectPath}
                privateKeyPath={privateKeyPath}
                appid={appid}
                type={type}
                onSelectDevProjectPath={handleSelectDevProjectPath}
                onSelectProdProjectPath={handleSelectProdProjectPath}
                onSelectPrivateKeyPath={handleSelectPrivateKeyPath}
                onAppidChange={setAppid}
                onTypeChange={setType}
                onSaveConfig={handleSaveConfig}
                loading={loading}
              />
            </TabsContent>

            <TabsContent value="upload">
              <UploadSection
                projectPath={prodProjectPath}
                privateKeyPath={privateKeyPath}
                appid={appid}
                type={type}
                showToast={showToast}
                setLoading={setLoading}
              />
            </TabsContent>

            <TabsContent value="preview">
              <PreviewSection
                projectPath={devProjectPath}
                privateKeyPath={privateKeyPath}
                appid={appid}
                type={type}
                showToast={showToast}
                setLoading={setLoading}
              />
            </TabsContent>

            <TabsContent value="npm">
              <NpmBuildSection
                projectPath={devProjectPath}
                privateKeyPath={privateKeyPath}
                appid={appid}
                type={type}
                showToast={showToast}
                setLoading={setLoading}
              />
            </TabsContent>
          </Tabs>

          {toast.show && (
            <Toast className={`
              ${toast.type === 'success' ? 'bg-green-50 text-green-800' : ''}
              ${toast.type === 'error' ? 'bg-red-50 text-red-800' : ''}
              ${toast.type === 'info' ? 'bg-blue-50 text-blue-800' : ''}
            `}>
              <ToastTitle>{toast.title}</ToastTitle>
              <ToastDescription>{toast.description}</ToastDescription>
            </Toast>
          )}
          <ToastViewport />
        </ToastProvider>
      </div>
    </div>
  );
};

export default App;
